<template>
  <div class="page-container">
    <el-container style="min-height: 100vh;">
      <el-main style="display: flex; align-items: center; justify-content: center; padding: 20px;">
        <el-card style="width: 400px; max-width: 90%;" shadow="always">
          <!-- Page Title -->
          <template #header>
            <div style="text-align: center;">
              <h1 style="margin: 0; font-size: 28px; color: #303133; margin-bottom: 8px;">
                Order System
              </h1>
              <p style="margin: 0; color: #909399; font-size: 16px;">
                Order Management System
              </p>
            </div>
          </template>

          <!-- Login Form -->
          <el-form
            ref="formRef"
            :model="loginForm"
            :rules="rules"
            label-width="0"
            size="large"
            @submit.prevent="handleLogin"
          >
            <!-- Email Input -->
            <el-form-item prop="email">
              <el-input
                v-model="loginForm.email"
                type="email"
                placeholder="Enter your email"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>

            <!-- Password Input -->
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="Enter your password"
                :prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>

            <!-- Google Authentication -->
            <el-form-item>
              <el-text style="margin-bottom: 8px; display: block;">Google Authentication</el-text>
              <GoogleLoginButton
                @success="handleGoogleSuccess"
                @error="handleGoogleError"
              />
            </el-form-item>

            <!-- Captcha Input -->
            <el-form-item prop="verificationCode">
              <el-input
                v-model="loginForm.verificationCode"
                placeholder="Enter verification code"
                maxlength="6"
                clearable
              >
                <template #append>
                  <el-button @click="generateVerificationCode">
                    {{ verificationCode || 'Generate' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <!-- Login Button -->
            <el-form-item>
              <el-button
                type="primary"
                style="width: 100%;"
                :loading="authStore.isLoading"
                :disabled="!isFormValid"
                @click="handleLogin"
              >
                {{ authStore.isLoading ? 'Signing in...' : 'Sign In' }}
              </el-button>
            </el-form-item>

            <!-- Error Message -->
            <el-alert
              v-if="authStore.error"
              :title="authStore.error"
              type="error"
              show-icon
              :closable="false"
              style="margin-bottom: 16px;"
            />

            <!-- Divider -->
            <el-divider>
              <span style="color: #909399; font-size: 14px;">Don't have an account?</span>
            </el-divider>

            <!-- Register Button -->
            <el-form-item>
              <el-button
                style="width: 100%;"
                @click="showRegisterForm = !showRegisterForm"
              >
                Create Account
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { User, Lock } from '@element-plus/icons-vue'
import GoogleLoginButton from '../components/GoogleLoginButton.vue'
import type { FormInstance, FormRules } from 'element-plus'

// Router and store
const router = useRouter()
const authStore = useAuthStore()
const toast = useToast()

// Form reference
const formRef = ref<FormInstance>()

// Form data
const loginForm = ref({
  email: '',
  password: '',
  verificationCode: ''
})

// Captcha
const verificationCode = ref('')
const showRegisterForm = ref(false)

// Form validation rules
const rules: FormRules = {
  email: [
    { required: true, message: 'Email is required', trigger: 'blur' },
    { type: 'email', message: 'Please enter a valid email address', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Password is required', trigger: 'blur' },
    { min: 6, message: 'Password must be at least 6 characters', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: 'Verification code is required', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== verificationCode.value) {
          callback(new Error('Invalid verification code'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// Computed properties
const isFormValid = computed(() => {
  return loginForm.value.email &&
         loginForm.value.password &&
         loginForm.value.verificationCode &&
         loginForm.value.verificationCode === verificationCode.value
})

// Generate captcha
function generateVerificationCode() {
  verificationCode.value = Math.random().toString().slice(2, 8)
}

// Handle login
async function handleLogin() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await authStore.login({
          email: loginForm.value.email,
          password: loginForm.value.password
        })

        // Login successful, redirect to dashboard
        const redirect = router.currentRoute.value.query.redirect as string
        router.push(redirect || '/dashboard')
      } catch (error) {
        // Error has been handled and displayed in store
        console.error('Login failed:', error)
      }
    }
  })
}

// Handle Google authentication success
function handleGoogleSuccess(result: any) {
  // Google authentication successful, user logged in
  authStore.user = result.user
  authStore.token = result.token

  // Save to local storage
  localStorage.setItem('auth_token', result.token)
  localStorage.setItem('auth_user', JSON.stringify(result.user))

  // Redirect to dashboard
  const redirect = router.currentRoute.value.query.redirect as string
  router.push(redirect || '/dashboard')
}

// Handle Google authentication error
function handleGoogleError(error: string) {
  console.error('Google auth failed:', error)
  // Error has been displayed in GoogleLoginButton component
}

// Generate captcha when component mounts
onMounted(() => {
  generateVerificationCode()

  // If already logged in, redirect to dashboard
  if (authStore.isAuthenticated) {
    router.push('/dashboard')
  }
})
</script>
